package com.cloudclassroom.auth;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.cloudclassroom.entity.Admin;
import com.cloudclassroom.mapper.AdminMapper;
import lombok.RequiredArgsConstructor;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

/**
 * @author 92110
 */
@Service
@RequiredArgsConstructor
public class AdminLoginServiceImpl implements UserDetailsService {

    private final AdminMapper adminMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        Admin admin = adminMapper.selectOne(new QueryWrapper<Admin>().eq("username", username));
        if (admin == null) {
            throw new UsernameNotFoundException("用户名不存在");
        } else {
            return org.springframework.security.core.userdetails.User
                    .withUsername(admin.getUsername())
                    .password(admin.getPassword())
                    .roles(admin.getRole())
                    .build();
        }
    }
}
